package com.zky.gulimall.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zky.common.constant.AuthServerConstant;
import com.zky.common.utils.HttpUtils;
import com.zky.common.utils.R;
import com.zky.gulimall.authserver.feign.MemberFeignService;
import com.zky.common.vo.MemberRespVo;
import com.zky.gulimall.authserver.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description OAuth2相关，社交登录
 * @Author 张开源
 * @Date 2022/11/26 21:49
 * @Version 1.0
 **/
@Controller
@Slf4j
public class OAuth2Controller {
    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weiBo(@RequestParam("code") String code, HttpSession session) throws Exception {
        log.warn("code:"+code);
        //根据code获取accessToken
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "1892918350");
        map.put("client_secret", "cb646bcbf0338cf1f167f1a3bb4ed6df");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.zky.com/oauth2.0/weibo/success");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", null, null, map);
        //远程登陆
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //登陆或者注册
            R oauth2Login = memberFeignService.oauth2Login(socialUser);
            if (oauth2Login.isSuccess()) {
                String data = JSON.toJSONString(oauth2Login.get("data"));
                MemberRespVo memberRespVo = JSON.parseObject(data, new TypeReference<MemberRespVo>() {
                });
                session.setAttribute(AuthServerConstant.LOGIN_USER,memberRespVo);
                log.warn(" login success,memberRespVo:" + memberRespVo);
                //若是第一次登陆进来，需要关联会员信息
                return "redirect:http://zky.com";
            }
        }
        //登陆失败回到登陆页
        return "redirect:http://auth.zky.com/login.html";
    }
}
